<template>
  <div class="login-container">
    <div class="login-logo">WMS</div>
    
    <div class="login-content">
      <div class="login-banner">
        <img src="@/assets/images/login-banner.png" alt="仓库管理系统插图">
      </div>
      
      <div class="login-form-container" v-if="!showWarehouseSelect">
        <div class="login-form-header">
          <h2>您好！欢迎登录</h2>
          <h3>测试WMS系统</h3>
        </div>
        
        <div class="login-form-tabs">
          <div 
            :class="['tab-item', activeTab === 'password' ? 'active' : '']" 
            @click="activeTab = 'password'"
          >
            密码登录
          </div>
          <div 
            :class="['tab-item', activeTab === 'captcha' ? 'active' : '']" 
            @click="activeTab = 'captcha'"
          >
            验证码登录
          </div>
        </div>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules"
          class="login-form"
        >
          <!-- 账号输入框 -->
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入手机号" 
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 密码输入框 - 密码登录模式 -->
          <el-form-item v-if="activeTab === 'password'" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码" 
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 图形验证码 - 密码登录模式 -->
          <el-form-item v-if="activeTab === 'password'" prop="imageCaptcha">
            <div class="captcha-container">
              <el-input 
                v-model="loginForm.imageCaptcha" 
                placeholder="请输入右侧验证码" 
              />
              <div class="image-captcha" @click="refreshImageCaptcha">
                {{ imageCaptcha }}
              </div>
            </div>
          </el-form-item>
          
          <!-- 验证码输入框 - 验证码登录模式 -->
          <el-form-item v-if="activeTab === 'captcha'" prop="captcha">
            <div class="captcha-container">
              <el-input 
                v-model="loginForm.captcha" 
                placeholder="请输入验证码" 
              />
              <el-button type="primary" :disabled="isCaptchaLoading" @click="handleSendCaptcha">
                {{ captchaButtonText }}
              </el-button>
            </div>
          </el-form-item>
          
          <!-- 登录按钮 -->
          <el-button 
            type="primary" 
            class="login-button" 
            :loading="isLoading" 
            @click="handleLogin"
          >
            登录
          </el-button>
		  
		  <!-- 记住密码和忘记密码 -->
		  <div class="login-options">
		    <el-checkbox v-model="rememberPassword">30天免登录</el-checkbox>
			<el-checkbox v-model="rememberUsername">记住密码</el-checkbox>
		    <el-link type="primary" @click="goToForgotPassword">忘记密码</el-link>
		  </div>
        </el-form>
      </div>

      <!-- 选择仓库界面 -->
      <div v-else class="warehouse-select-container">
        <div class="warehouse-select-header">
          <div class="back-to-login" @click="backToLogin">
            <el-icon><Back /></el-icon>
            返回登录
          </div>
          <h3>请选择仓库</h3>
        </div>
        
        <div class="warehouse-list">
          <div 
            v-for="(warehouse, index) in warehouseList" 
            :key="index" 
            class="warehouse-item"
            :class="{ 'selected': selectedWarehouse === warehouse.id }"
            @click="selectWarehouse(warehouse)"
          >
            {{ warehouse.name }}
            <el-icon v-if="selectedWarehouse === warehouse.id"><Check /></el-icon>
          </div>
        </div>

        <el-button 
          type="primary" 
          class="confirm-button" 
          :disabled="!selectedWarehouse" 
          @click="confirmWarehouse"
        >
          确认
        </el-button>
      </div>
    </div>
    
    <!-- <div class="login-footer">
      <span>如遇问题，联系客服热线</span>
      <span class="login-footer-phone">	400-6529088</span>
    </div> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Back, Check } from '@element-plus/icons-vue'

const router = useRouter()

// 登录表单相关
const loginFormRef = ref(null)
const activeTab = ref('password')
const rememberPassword = ref(false)
const rememberUsername = ref(false)
const isLoading = ref(false)
const isCaptchaLoading = ref(false)
const captchaButtonText = ref('发送验证码')
const imageCaptcha = ref('36+22')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  imageCaptcha: ''
})

// 选择仓库相关
const showWarehouseSelect = ref(false)
const selectedWarehouse = ref('')
const warehouseList = ref([
  { id: '1', name: '华东上海仓' },
  { id: '2', name: '华东苏州仓' },
  { id: '3', name: '华东杭州仓' },
  { id: '4', name: '华东厦门仓' },
  { id: '5', name: '华东南京仓' },
])

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  imageCaptcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ]
})

// 刷新图形验证码
const refreshImageCaptcha = () => {
  // 生成简单的计算题
  const num1 = Math.floor(Math.random() * 50) + 10
  const num2 = Math.floor(Math.random() * 20) + 10
  imageCaptcha.value = `${num1}+${num2}`
}

// 发送短信验证码
const handleSendCaptcha = () => {
  if (!loginForm.username) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  // 校验手机号格式
  if (!/^1[3-9]\d{9}$/.test(loginForm.username)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  
  isCaptchaLoading.value = true
  captchaButtonText.value = '发送中...'
  
  // 模拟发送验证码请求
  setTimeout(() => {
    ElMessage.success(`验证码已发送至 ${loginForm.username}`)
    isCaptchaLoading.value = false
    
    // 倒计时
    let count = 60
    captchaButtonText.value = `${count}s`
    const timer = setInterval(() => {
      count--
      captchaButtonText.value = `${count}s`
      if (count <= 0) {
        clearInterval(timer)
        captchaButtonText.value = '发送验证码'
        isCaptchaLoading.value = false
      }
    }, 1000)
  }, 1500)
}

// 登录处理
const handleLogin = () => {
  if (!loginFormRef.value) return
  
  loginFormRef.value.validate(valid => {
    if (!valid) return
    
    isLoading.value = true
    
    // 模拟登录请求
    setTimeout(() => {
      // 验证用户名密码，实际项目中应该调用接口
      const isValidUser = true
      
      if (isValidUser) {
        // 存储token
        localStorage.setItem('token', 'demo-token-abc123')
        
        if (rememberPassword.value) {
          // 设置记住登录的信息，实际项目中可以使用加密方式存储
          localStorage.setItem('rememberLogin', JSON.stringify({
            username: loginForm.username,
            expires: Date.now() + 30 * 24 * 60 * 60 * 1000 // 30天后过期
          }))
        }
        
        if (rememberUsername.value) {
          // 记住用户名和密码
          localStorage.setItem('rememberCredentials', JSON.stringify({
            username: loginForm.username,
            password: loginForm.password
          }))
        } else {
          localStorage.removeItem('rememberCredentials')
        }
        
        ElMessage.success('登录成功')
        // 登录成功后显示选择仓库界面
        showWarehouseSelect.value = true
        isLoading.value = false
      } else {
        ElMessage.error('用户名或密码错误')
        isLoading.value = false
      }
    }, 1500)
  })
}

// 前往忘记密码页面
const goToForgotPassword = () => {
  console.log('正在跳转到忘记密码页面...');
  router.push({ path: '/forgot-password' });
}

// 返回登录页面
const backToLogin = () => {
  showWarehouseSelect.value = false
  selectedWarehouse.value = ''
}

// 选择仓库
const selectWarehouse = (warehouse) => {
  selectedWarehouse.value = warehouse.id
}

// 确认选择仓库
const confirmWarehouse = () => {
  if (!selectedWarehouse.value) {
    ElMessage.warning('请选择仓库')
    return
  }
  
  // 保存选择的仓库信息
  const selected = warehouseList.value.find(item => item.id === selectedWarehouse.value)
  localStorage.setItem('selectedWarehouse', JSON.stringify(selected))
  
  ElMessage.success('仓库选择成功')
  router.push('/')
}

// 检查是否有记住登录信息
onMounted(() => {
  const rememberLogin = localStorage.getItem('rememberLogin')
  if (rememberLogin) {
    try {
      const data = JSON.parse(rememberLogin)
      if (data.expires > Date.now()) {
        // 未过期，自动填充用户名
        loginForm.username = data.username
        rememberPassword.value = true
      } else {
        // 已过期，清除记住登录信息
        localStorage.removeItem('rememberLogin')
      }
    } catch (e) {
      localStorage.removeItem('rememberLogin')
    }
  }
  
  // 检查是否记住用户名密码
  const rememberCredentials = localStorage.getItem('rememberCredentials')
  if (rememberCredentials) {
    try {
      const credentials = JSON.parse(rememberCredentials)
      loginForm.username = credentials.username
      loginForm.password = credentials.password
      rememberUsername.value = true
    } catch (e) {
      localStorage.removeItem('rememberCredentials')
    }
  }
  
  // 初始化图形验证码
  refreshImageCaptcha()
})
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background-image: url('@/assets/images/background-img.png');
  background-size: cover;
  background-position: center;
}

.login-logo {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 32px;
  font-weight: bold;
  color: #0165FF;
}

.login-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  padding: 0 20px;
}

.login-banner {
  flex: 1;
  max-width: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
  
  img {
    width: 100%;
    max-width: 600px;
  }
}

.login-form-container, .warehouse-select-container {
  width: 400px;
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.login-form-header {
  text-align: left;
  margin-bottom: 30px;
  
  h2 {
    font-size: 24px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
  }
  
  h3 {
    font-size: 18px;
    font-weight: normal;
    color: #606266;
  }
}

.login-form-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  
  .tab-item {
    padding: 0 10px 10px;
    margin-right: 20px;
    cursor: pointer;
    font-size: 16px;
    color: #606266;
    
    &.active {
      color: #0165FF;
      font-weight: 500;
      border-bottom: 2px solid #0165FF;
    }
  }
}

.login-form {
  .captcha-container {
    display: flex;
    
    .el-input {
      flex: 1;
      margin-right: 10px;
    }
    
    .el-button {
      width: 120px;
    }
    
    .image-captcha {
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background: #f5f7fa;
      color: #303133;
      font-size: 20px;
      font-weight: bold;
      cursor: pointer;
      user-select: none;
      border-radius: 4px;
    }
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.login-button, .confirm-button {
  width: 100%;
  margin-top: 20px;
  padding: 12px 0;
  font-size: 16px;
  background-color: #0165FF;
  border-color: #0165FF;
  
  &:hover, &:focus {
    background-color: #1975ff;
    border-color: #1975ff;
  }
}

.login-footer {
  text-align: center;
  padding: 20px 0;
  color: #606266;
  font-size: 16px;
  &-phone{
	  color: #0165FF;
	  font-weight:600;
  }
}

// 仓库选择样式
.warehouse-select-header {
  position: relative;
  margin-bottom: 30px;
  text-align: center;
  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
  
  .back-to-login {
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    color: #0165FF;
    cursor: pointer;
    font-size: 14px;
    
    .el-icon {
      margin-right: 4px;
    }
  }
}

.warehouse-list {
  margin-top: 20px;
}

.warehouse-item {
  position: relative;
  padding: 12px 16px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  &:hover {
    border-color: #0165FF;
  }
  
  &.selected {
    border-color: #0165FF;
    color: #0165FF;
    background-color: #F0F7FF;
  }
}

// 响应式处理
@media (max-width: 1200px) {
  .login-banner {
    display: none;
  }
  
  .login-form-container, .warehouse-select-container {
    width: 100%;
    max-width: 400px;
  }
}
</style> 